package com.example.tangyee.utils;

import android.os.AsyncTask;
import android.util.Log;

import com.example.tangyee.bean.Doctor;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

public class GetDoctors extends AsyncTask<Void, Void, List<Doctor>> {

    private static final String TAG = "GetDoctors";

    private OnPostExecute mExecute;

    public GetDoctors(OnPostExecute execute){
        this.mExecute = execute;
    }

    @Override
    protected List<Doctor> doInBackground(Void... voids) {
        if (isCancelled()) {
            return null;
        }
        // 采用get的方式访问url
        List<Doctor> doctors = new ArrayList<>();
        try {
            Document document = Jsoup.connect(ConstantsUtil.GET_DOCTORS).get();
            Elements lis = document.select("ul.mui-table-view>li");
            for (Element li : lis) {
                Doctor doctor = new Doctor();

                String detailUrl = li.getElementsByAttribute("href").first().attr("href");
                doctor.setDetailUrl(detailUrl);

                String image = li.getElementsByAttribute("src").first().attr("src");
                doctor.setImgUrl(image);

                String name = li.select("h2").text();
                doctor.setName(name);

                doctors.add(doctor);
                // Prefect
                Log.i(TAG, "doInBackground: " + doctor.toString());
            }
        } catch (SocketTimeoutException ste) {
            Log.e(TAG, "doInBackground: ", ste);
            return null;
        } catch (IOException e) {
            Log.e(TAG, "doInBackground: ", e);
            return null;
        }

        return doctors;
    }

    @Override
    protected void onPostExecute(List<Doctor> doctors) {
        mExecute.onPostExecute(doctors);
    }


    public void setOnPostExecute(OnPostExecute execute) {
        this.mExecute = execute;
    }

    public interface OnPostExecute {
        void onPostExecute(List<Doctor> doctors);
    }
}
